package com.atguigu.srb.sms.controller;

import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.common.util.RandomUtils;
import com.atguigu.srb.common.util.RegexValidateUtils;
import com.atguigu.srb.sms.client.CoreUserInfoClient;
import com.atguigu.srb.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lwm1435@163.com
 * @date 2022-02-11 17:30
 * @description
 */
@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
@Slf4j
public class SmsController {
    @Resource
    private SmsService smsService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private CoreUserInfoClient client;

    @ApiOperation("发送验证码")
    @GetMapping("/send/{mobile}")
    public R send(@PathVariable String mobile) {
        //是否为空
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        //是否为合法手机号
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);

        //远程调用Core服务验证手机号是否已经注册
        Boolean result = client.checkMobile(mobile);
        log.info("远程调用结果:{}", result);
        Assert.isTrue(!result, ResponseEnum.MOBILE_EXIST_ERROR);

        //随机四位数字
        String code = RandomUtils.getFourBitRandom();
        log.info("短信验证码：{}", code);
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
//        //通过阿里云API发送短信
//         smsService.sendSms(mobile, param);

        //验证码存入redis
        redisTemplate.opsForValue().set("code:" + mobile, code, 10, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }
}
